package cn.com.hnisi.springldap;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class XmlOp {

	/** 存放xml文件路径 */
	private static final String XML_ROOT_PATH = "E:/datas/";

	/**
	 * 导出数据库记录到xml文件
	 * 
	 * @param table
	 * @param columns
	 * @param records
	 */
	public static void export2Xml(List<Person> persons) {
		try {
			Document doc = DocumentHelper.createDocument();
			// 根元素data
			Element entrysEl = doc.addElement("entrys");
			doc.setRootElement(entrysEl);
			// userEl.addAttribute("tablename", table);
			// userEl.addAttribute("createTableSql", createTableSql);
			// userEl.addAttribute("createPkSql", createPkSql);
			for (Person e : persons) {
				Element userEl = entrysEl.addElement("user");
				Element cnEl = userEl.addElement("cn");
				cnEl.setText(e.getCn() != null ? e.getCn() : "");
				Element uidEl = userEl.addElement("uid");
				uidEl.setText(e.getUid() != null ? e.getUid() : "");
				Element mailEl = userEl.addElement("mail");
				mailEl.setText(e.getMail() != null ? e.getMail() : "");
				Element maildomainEl = userEl.addElement("maildomain");
				maildomainEl.setText(e.getMaildomain() != null ? e
						.getMaildomain() : "");
				Element snEl = userEl.addElement("sn");
				snEl.setText(e.getSn() != null ? e.getSn() : "");
			}
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("utf-8"); // 设置XML文档的编码类型
			format.setSuppressDeclaration(true);
			format.setIndent(true); // 设置是否缩进
			format.setIndent("\t"); // 设置缩进方式
			format.setNewlines(true); // 设置是否换行
			XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(new File(
					XML_ROOT_PATH + "users.xml")), format);// 创建XML文档（写）
			xmlWriter.write(entrysEl);
			xmlWriter.close();
		} catch (IOException e) {
			System.err.println("生成XML文件出错");
			e.printStackTrace();
		}
	}
}
